package main

import (
	"fmt"
	"github.com/boltdb/bolt"
	"whoscored/util/boltdb"

	"strings"
	"encoding/json"
	"whoscored/util/mysql"

)

func teamData(data map[string]interface{})([]interface{},map[string]interface{})  {
	teamId:=data["id"]
	name:=data["name"]
	shortName:=data["shortName"]
	rating:=data["rating"]
	formation:=data["formation"]
	stats:=data["stats"].(map[string]interface{})
	d:=[]interface{}{teamId,name,shortName,rating,formation,}
	return d,stats
}

func teamMatch(m map[string]interface{},info map[string]interface{},match string)  {
	sql:="insert into team_match(matchId,regionName,regionCode,tournamentName,startTimeUtc,homeScore,awayScore,teamId,name,shortName,rating,formation,shots," +
		"offsides,corners,tackles,throwins,dribblesWon,totalPasses,passAccuracy,aerialsWon,ballPossession,shotsOnTarget," +
		"goals,shotsOffTarget,hitWoodwork,shotsBlocked,isHome,season) " +
		"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
	matchId := m["id"].(float64)

	regionName := info["regionName"]
	regionCode := info["regionCode"]
	tournamentName := info["tournamentName"]
	t1 := strings.Split(info["startTimeUtc"].(string), ".")
	t2 := strings.Split(t1[0], "T")
	startTimeUtc := t2[0] + " " + t2[1]
	homeScore := info["homeScore"].(float64)
	awayScore := info["awayScore"].(float64)

	//liveMatch
	liveMatch := m["liveMatch"].(map[string]interface{})
	liveStatistics := liveMatch["liveStatistics"].(map[string]interface{})
	home := liveStatistics["home"].(map[string]interface{})
	away:=liveStatistics["away"].(map[string]interface{})

	mmJson:=make(map[string]interface{},0)

	json.Unmarshal([]byte(match),&mmJson)
	region:=mmJson["region"].([]interface{})
	season:=region[12].(string)
	dataHome, statsHome := teamData(home)
	mysql.Insert(sql, matchId, regionName, regionCode, tournamentName, startTimeUtc, homeScore, awayScore,
		dataHome[0], dataHome[1], dataHome[2], dataHome[3], dataHome[4],
		statsHome["shots"], statsHome["offsides"], statsHome["corners"], statsHome["tackles"], statsHome["throwins"],
		statsHome["dribblesWon"], statsHome["totalPasses"], statsHome["passAccuracy"], statsHome["aerialsWon"],
		statsHome["ballPossession"], statsHome["shotsOnTarget"], statsHome["goals"],
		statsHome["shotsOffTarget"], statsHome["hitWoodwork"], statsHome["shotsBlocked"], 1, season,
	)
	dataAway, statsAway := teamData(away)
	mysql.Insert(sql, matchId, regionName, regionCode, tournamentName, startTimeUtc, homeScore, awayScore,
		dataAway[0], dataAway[1], dataAway[2], dataAway[3], dataAway[4],
		statsAway["shots"], statsAway["offsides"], statsAway["corners"], statsAway["tackles"], statsAway["throwins"],
		statsAway["dribblesWon"], statsAway["totalPasses"], statsAway["passAccuracy"], statsAway["aerialsWon"],
		statsAway["ballPossession"], statsAway["shotsOnTarget"], statsAway["goals"],
		statsAway["shotsOffTarget"], statsAway["hitWoodwork"], statsAway["shotsBlocked"], 0, season,
	)
	homePlayers:=home["players"].([]interface{})
	awayPlayers:=away["players"].([]interface{})
	homeWinScore:=homeScore-awayScore
	awayWinScore:=awayScore-homeScore
	teamPlayer(matchId,dataHome[0],season,startTimeUtc,homePlayers,1,homeWinScore)
	teamPlayer(matchId,dataAway[0],season,startTimeUtc,awayPlayers,0,awayWinScore)
}
func teamPlayer(matchId float64,teamId interface{},season string,startTimeUtc string,players []interface{},isHome int,matchWinScore float64){
	sql:="insert into player_match(matchId,playerId,teamId,shirtNo,name,height,weight,rating,shortName,age," +
		"isSub,isSubbedIn,isSubbedOut,isMoM,startTimeUtc,season,man_of_the_match,formation_place,total_sub_on," +
		"total_sub_off,position,totalPasses,passAccuracy,aerialsWon,touches,fouls,shots,dribblesWon,tackles," +
		"saves,assist,goal_penalty,goals,goal_own,penalty_missed,minutes_played,shots_blocked,was_dribbled,interceptions," +
		"was_fouled,offsides,dispossessed,turnovers,crosses,long_balls,through_balls,shotsOnTarget," +
		"yellow,red,secondYellow,penaltySave,error_lead_to_goal,last_man_tackle,clearance_off_line,hit_woodwork,isHome,matchWinScore) " +
		"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"

	for _,v:=range players{
		player:=v.(map[string]interface{})
		playerStats:=player["stats"].(map[string]interface{})
		mysql.Insert(sql,matchId,player["id"],teamId,player["shirtNo"],player["name"],player["height"],player["weight"],
			player["rating"],player["shortName"],player["age"],player["isSub"],player["isSubbedIn"],player["isSubbedOut"],
			player["isMoM"],startTimeUtc,season,
			playerStats["man_of_the_match"],playerStats["formation_place"],playerStats["total_sub_on"],playerStats["total_sub_off"],
			playerStats["position"],playerStats["totalPasses"],playerStats["passAccuracy"],playerStats["aerialsWon"],
			playerStats["touches"],playerStats["fouls"],playerStats["shots"],playerStats["dribblesWon"],
			playerStats["tackles"],playerStats["saves"],playerStats["assist"],playerStats["goal_penalty"],
			playerStats["goals"],playerStats["goal_own"],playerStats["penalty_missed"],playerStats["minutes_played"],
			playerStats["shots_blocked"],playerStats["was_dribbled"],playerStats["interceptions"],playerStats["was_fouled"],
			playerStats["offsides"],playerStats["dispossessed"],playerStats["turnovers"],playerStats["crosses"],
			playerStats["long_balls"],playerStats["through_balls"],playerStats["shotsOnTarget"],playerStats["yellow"],
			playerStats["red"],playerStats["secondYellow"],playerStats["penaltySave"],playerStats["error_lead_to_goal"],
			playerStats["last_man_tackle"],playerStats["clearance_off_line"],playerStats["hit_woodwork"],
			isHome,matchWinScore,
		)
	}

}
func main()  {
	i:=0
	j:=0


	boltdb.ScanTx("player-2015", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {

			b.ForEach(func(k, v []byte) error {

					if strings.Contains(string(v), "liveStatistics") {
						m := make(map[string]interface{}, 0)
						json.Unmarshal(v, &m)
						info := m["info"].(map[string]interface{})
						t1 := strings.Split(info["startTimeUtc"].(string), ".")
						t2 := strings.Split(t1[0], "T")

						bucket:=strings.Replace(t2[0],"-","",-1)

						boltdb.Get("matchs-2015",bucket,string(k), func(mm string) {
							teamMatch(m,info,mm)
							i++
							fmt.Println(i)
						})

					}
					j++

				return nil

			})
			return nil
		})
	})
	fmt.Println(i,j)
}
